#!/usr/bin/perl

$token = shift;
$key = shift;
$result = shift;
die "Could not open $key\n" if (!open(F,$key));
die "Could not open $result\n" if (!open(G,$result));

$total_recall=$total_precision=0;
$total_ans=$total_correct=$total_key=0;
$total_sent=0;

while(<F>) {
    chop;
    $key_len=0; %wkey=(); %wsrikey=();
    foreach $w  (&tokens($_,$token)) {
#	print "$w\n";
	$wkey{$w}++;
	$wsrikey{$w}=1;
	$key_len++;
    }

    $res=<G>;
    chop($res);

    $res_len=0; %wres=(); %wsrires=();
    foreach $w  (&tokens($res,$token)) {
#	print "$w\n";
	$wres{$w}++;
	$wsrires{$w}=1;
	$res_len++;
    }


    #print STDERR "Words predicted correctly: ";
    $correct=0;
    $recall=0; $precision=0;
    $flag =0;   # sriram 
    foreach $w (sort keys %wkey) {
        $flag=0;
	for($i=1;$i<=$wkey{$w};$i++) {
	    if ((exists $wres{$w}) && ($wres{$w} > 0)) {
		$correct++;
		$wres{$w}--;
		$flag=1;
	    }
	}
       # if($flag==1) { print STDERR $w." "; }
    }
	#print STDERR "\n";

    #print STDERR "Words not predicted: ";
    foreach $w (sort keys %wsrikey) {
	    if ((exists $wsrires{$w}) && ($wsrires{$w} > 0)) {
	    }
	    else {
		#print  STDERR "$w ";
	     }
	}
	#print STDERR "\n";

    #print STDERR "Words predicted incorrectly: ";
    foreach $w (sort keys %wsrires) {
	    if ((exists $wsrikey{$w}) && ($wsrikey{$w} > 0)) {
	    }
	    else {
		#print  STDERR "$w ";
	     }
	}
	#print STDERR "\n";

    $total_ans+=$res_len;
    $total_key+=$key_len;
    $total_correct+=$correct;

    $recall = $correct/$key_len if ($key_len > 0);
    $precision = $correct/$res_len if ($res_len > 0);

    $per=(compute_Max($res_len,$key_len) - $correct)/$key_len if ($key_len>0);
    #print "Key = $key_len Ans = $res_len Correct = $correct Recall = $recall Precision = $precision PER=$per\n";
	#print "\n\n";

    $total_per+=$per;
    $total_sent++;
}

$total_recall = $total_correct/$total_key if ($total_key > 0);
$total_precision = $total_correct/$total_ans if ($total_ans > 0);
$f = 2*$total_recall*$total_precision/($total_recall+$total_precision);
$avePER=$total_per/$total_sent;

print "\nKey = $total_key  Ans = $total_ans Correct = $total_correct Recall = $total_recall Precision = $total_precision F=$f Average PER=$avePER\n";

sub compute_Max {
    my ($n1,$n2) = @_;
    if ($n1 >= $n2) {return $n1;} else {return $n2};
}

sub tokens {
    local ($str, $token) = @_;
    local ($i,$j);
    local (@w)=();
    local (@res)=();
    if ($token =~ /w/i) {
	return split(' ',$str);
    }
    elsif ($token =~ /u/i) {
	@w=split('',$str);
	for($i=0;$i<=$#w;) {
	    if ($w[$i] eq " ") {
		$i++;
	    }
	    elsif (ord($w[$i]) < 227) { # this is an ascii chr.
		$res[$j++]=$w[$i];
		$i++;
	    }
	    else {
		$res[$j++]=join('',@w[$i..$i+2]);
		$i+=3;
	    }
	}
	return @res;
    }
    else {
	return split('',$str);
    }
}
